package com.bootcamp.javase2.reflection;

import java.lang.reflect.Field;

/**
 * @program: day23ReflectionCode
 * @description:
 * @author: Keyu Li
 * @create: 2021-09-17 19:42
 **/

public class Work1 {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        // 测试修改变量值方法
        TestFieldUpdate obj = new TestFieldUpdate();
        // 输出修改前值
        System.out.println("修改前: ");
        System.out.println(obj);
        // 修改 3 个成员变量
        setAll(obj, "name", "new liming");
        setAll(obj, "gender", "new male");
        setAll(obj, "age", 44);
        System.out.println("修改后：");
        System.out.println(obj);
    }


    /**
     * @param targetObj 要修改成员变量值的目标对象
     * @param fieldName 对象中要修改的成员变量的名字
     * @param newValue  要修改成员变量值的新值
     */

    public static void setAll(Object targetObj, String fieldName, Object newValue)
            throws NoSuchFieldException, IllegalAccessException {
        Class objClass = targetObj.getClass();
        // 找到指定名称的 field
        Field objField = objClass.getDeclaredField(fieldName);
        // 保证有权限修改
        objField.setAccessible(true);
        // 修改为指定的新值
        objField.set(targetObj, newValue);
    }
}

class TestFieldUpdate {
    public String name = "liming";
    private String gender = "male";
    private int age = 15;

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("TestFieldUpdate{");
        sb.append("name='").append(name).append('\'');
        sb.append(", gender='").append(gender).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
    }
}
